package com.itheima.rocketmq.rocketmqdemo.order.refer.wangluo;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 顺序消息消费，带事务方式（应用可控制Offset什么时候提交）
 * 接受消息的不一致性：
 * 发送消息的时候，消息发送默认是会采用轮询的方式发送到不通的queue（分区）
 * 消费端从多个queue是同时拉取提交消费
 */
public class ConsumerInOrder {

    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_3");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        /**
         * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
         * 如果非第一次启动，那么按照上次消费的位置继续消费
         */
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        consumer.subscribe("TopicTestjjj", "TagA || TagC || TagD");

        List<OrderDemo> list = new ArrayList<>();
        consumer.registerMessageListener(new MessageListenerOrderly() {

            Random random = new Random();

            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                context.setAutoCommit(true);
                for (MessageExt msg : msgs) {
//                    System.out.println(Thread.currentThread().getName() +"【"+ msg.getBornHostNameString() +"】【"+msg.getQueueOffset()+"】【"+ msg.getQueueId() +"】 content:" + new String(msg.getBody()));
//                    list.add(JSONObject.parseObject(msg.getBody(), OrderDemo.class));
                    OrderDemo orderDemo = JSONObject.parseObject(msg.getBody(), OrderDemo.class);
                    System.out.println("----");
                    if(orderDemo.getOrderId() == 15103111039L){
                        System.out.println(orderDemo.toString());
                    }
                }
//                try {
//                    //模拟业务逻辑处理中...
//                    TimeUnit.SECONDS.sleep(random.nextInt(10));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });

        consumer.start();
//        TimeUnit.SECONDS.sleep(100);
//        for (OrderDemo orderDemo:list) {
//            if(orderDemo.getOrderId() == 15103111039L){
//                System.out.println(orderDemo.toString());
//            }
//        }
    }
}